package com.qh.basic.controller;

import com.qh.basic.util.AjaxResult;
import com.qh.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.websocket.server.PathParam;
import java.nio.file.Path;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 文件上传【fastdfs】
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart MultipartFile file){
        try {
            //获取文件的原始路径[假设file = xxx.jpg]
            String originalFilename = file.getOriginalFilename();//xxx.jpg
            String exeName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);//jpg
            String fileName = FastDfsUtils.upload(file.getBytes(), exeName);
            return new AjaxResult(true,"上传成功",fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }


     /**
     * 删除接口
     * @return
     * delete http://localhost:8080/fastDfs?path=/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     */
    @DeleteMapping()
    public AjaxResult deleteFile(@RequestParam("path") String path){
        /* path=/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg */
        try {
            /* 分割 */
            path = path.substring(1);// [group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg]
            String groupName = path.substring(0, path.indexOf("/"));//[group1]
            String fileName = path.substring(path.indexOf("/") + 1);//[M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg]
            FastDfsUtils.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

}
